var app = getApp()
var fun = require('../fun.js');
Page({
  data: {
    nav:{top:app.globalData.nav_top,title:'发布详情',home:'show',back:'show',safe_top:app.globalData.safe_top,page:'my'},page:1,can_load:1,file_num:0,can_upload:1,hb_index:0
  },
   onLoad(op) {
      var from=op.from;
      if(!from){from='direct';}

      var id=op.id;if(!id){id=0;from='link';}//门店
      var from_id=op.f;if(!from_id){from_id=0;}//来源id
          if (op.scene) {//扫描
            var scene = decodeURIComponent(op.scene);
            var arrPara = scene.split("&");
            var arr = [];
            for (var i in arrPara) {
              arr = arrPara[i].split("=");
              if (arr[0] == 'f') { from_id = arr[1]; }//from_id
              if (arr[0] == 'id') { id=arr[1];}//门店id
            }
           from='scan';
          }
      app.globalData.from=from;
      app.globalData.from_id=from_id;
      this.data.from=from;
      if(!id){app.err('请指定消息详情');return;}
      this.data.id=id;//门店id
      

      fun.view_add('打开详情'+id+' from:'+from+' f_id:'+from_id);
   },

   onReady() {var that=this
this.get_pos();
this.load();
var pages=getCurrentPages();
this.setData({page_num:Object.keys(pages).length});
try {
   wx.checkIsAddedToMyMiniProgram({complete(res){
      if(!res.added){
      setTimeout(function(){that.setData({add_fav_show:1})},2000);
      setTimeout(function(){that.setData({add_fav_show:0})},12000);
   }
   }});
   }catch (e) { }
   },
   get_pos(e){
      var that=this;
      if(app.globalData.latitude){return;}
      fun.view_add('获取位置');
      console.log('获取位置信息')
fun.get_pos().then(res=>{
   if(res.err=='ok'){
      app.globalData.latitude=res.latitude; 
      app.globalData.longitude=res.longitude;
      var list=this.data.arc;
      if(list && list.lat){
        var  dis=fun.get_dis(list.lat,list.lng,res.latitude,res.longitude);
         this.setData({dis:dis})
      }
var more=this.data.list;
if(more){
for(var i in more){
if(more[i].lat){
  more[i]['dis']=fun.get_dis(more[i].lat,more[i].lng,res.latitude,res.longitude);
}

}
this.setData({list:more})
}

   }
})

   },
   onShow() {

      if(app.globalData.flash==1){this.load();app.globalData.flash=0;}
   },
   add_fav_show(e){
      this.setData({add_fav_show:0})
   },
   load() {fun.view_add('页面加载中 id:'+this.data.id);
   var that=this;
fun.get({ac:'get_detail',id:this.data.id,from:this.data.from}).then(res=>{fun.view_add('详细页加载完成');

   var dis=0;
if(res.list){
if(res.list.lat && app.globalData.latitude){console.log('获取位置')
   dis=fun.get_dis(res.list.lat,res.list.lng,app.globalData.latitude,app.globalData.longitude);
   console.log(dis)
   this.setData({dis:dis})
}
}
var more=res.more;
if(more && app.globalData.latitude){
for(var i in more){
   if(more[i].lat){
      more[i]['dis']=fun.get_dis(more[i].lat,more[i].lng,app.globalData.latitude,app.globalData.longitude);
   }
}
}

if(!app.globalData.region || !app.globalData.area){
var region=[res.list['pro'],res.list['city'],res.list['dist']];
var area=res.list['dist'];
app.globalData.region=region;
app.globalData.area=area;
console.log(area)
try {
   wx.setStorageSync('area',area);
   } catch (e) {}
  
   try {
     wx.setStorageSync('region',region);
     } catch (e) {}

}

this.setData({arc:res.list,set:res.set,user:res.user,warn:res.warn,list:more,fav:res.fav,info:res.info,c:res.c});
if(!res.user){
   app.globalData.user_id='';
   app.globalData.session='';
   fun.login().then(res=>{console.log(res)
      if(res.err=='ok'){
      this.setData({user:res.user});
      }
      if(res.is_new){
         this.setData({user_change_show:'show'})
      }
   })
}
//this.get_hb()
})
   },

   arc_go(e) {
var val=e.currentTarget.dataset.val;
this.data.id=val;
this.load()
   },
   img_preview(e){
      var list=this.data.arc;
      var index=e.currentTarget.dataset.index;
      var img=[];
      var current='';
      for(var i in list.img){
      img.push(list.img[i].img_750);
      if(i==index){current=list.img[i].img_750}
      }
      console.log(img,index)
      wx.previewImage({
        urls: img,
        current:current
      })
      
      },
      call(e){fun.view_add('电话联系');
var val=e.currentTarget.dataset.val;
var user=this.data.user;
if(!user){wx.navigateTo({
  url: '/pages/login/index',
});
return
}
wx.makePhoneCall({
  phoneNumber: val,
})  },

preview(e){
   var val=e.currentTarget.dataset.val;
   wx.previewImage({
     urls: [val],
   })
      },

qr_show(e){
   var val=e.currentTarget.dataset.val;
   wx.previewImage({
     urls: [val],
   })
app.msg('长按图片识别二维码');
},
fav_add(e){
   var id=e.currentTarget.dataset.id;
   var fav=this.data.fav;if(!fav){fav={}}
   console.log(id)
   fun.get({ac:'fav_add',id:id}).then(res=>{
      fav['item_'+id]=id;
      this.setData({fav:fav})
   })
   },
   onPullDownRefresh() {

   },
   val_change(e){
var val=e.detail.value;
if(val){
this.setData({is_edit:1})
}else{
this.setData({is_edit:0})
}
this.data.msg=val;

   },
   submit(e){
   var arc=this.data.arc;
   var msg=this.data.msg;
   if(!msg){app.err('请输入留言信息');return;}
var data={msg:msg,id:arc.id}
this.setData({is_edit:0});

fun.get({ac:'msg_submit',data:JSON.stringify(data)}).then(res=>{
   var info=this.data.info;
   msg=''
   this.setData({msg:msg})
app.err(info.msg_send);
})
   },
   check_suc(e){//审核成功
      var that=this;
      var list=this.data.arc;
      var index=e.currentTarget.dataset.index;
      wx.showModal({
        title: '提示',content:'是否审核成功',success(res){
      if(res.confirm){
      fun.get({ac:'adm_arc_check',id:list.id}).then(res=>{
       //  delete(list[index]);
         //that.setData({list:list});
         that.load()
         app.err('审核成功');
      })
      }
        }
      })
      
         },
         edit_it(e){//开启编辑
            var info=this.data.info;
            if(!info.is_adm){app.err('权限有误');return}
            var arc=this.data.arc;
            fun.get({ac:'get_edit',id:arc.id}).then(res=>{
               var day_now=0;
               if(res.data){
                
                  this.setData({edit_data:res.data});
                  var day=parseInt(res.data.days)
                  for(var i in res.days){
                     var x=parseInt(i);
                     if(i==day){
                        day_now=i;
                     }
                  }
               }
               this.setData({days:res.days,day_now:day_now,c_list:res.list,edit_show:'show'})


            })


         },
         c_select(e){
var edit_data=this.data.edit_data;
if(!edit_data){err('数据错误');return}
console.log(edit_data)
var val=e.currentTarget.dataset.val;
edit_data.c=val;
this.setData({edit_data:edit_data})
         },
         edit_change(e){
            var edit_data=this.data.edit_data;
            if(!edit_data){err('数据错误');return}
            var val=e.detail.value;
           // console.log(val)
            edit_data['html']=val;
            this.data.edit_data=edit_data


         },
         html_save(e){//保存
            var edit_data=this.data.edit_data;
            if(!edit_data){err('数据错误');return}  
            console.log(edit_data)
var data={html:edit_data.html,c:edit_data.c}
fun.get({ac:'submit_arc',data:JSON.stringify(data),id:edit_data.id}).then(res=>{
   this.load();
   this.setData({edit_show:'hide'})
   app.msg('保存成功')
})

         },
         sub_it(e){
var arc=this.data.arc;
var sub_data={phone:arc.phone,dist:arc.dist};
this.setData({sub_show:'show',sub_data:sub_data})


         },
         copy_temp(e){
var arc=this.data.arc;
wx.setClipboardData({
  data: arc.temp,
})
         },


         sub_change(e){
var val=e.detail.value;
var sub_data=this.data.sub_data;if(!sub_data){app.err('数据错误');return}
var c=e.currentTarget.dataset.c;
console.log(c,val)
sub_data[[c]]=val;
this.data.sub_data=sub_data
         },
         select_sub_c(e){
            var val=e.currentTarget.dataset.val;
            var sub_data=this.data.sub_data;if(!sub_data){app.err('数据错误');return}
           
            sub_data['c']=val;
            this.setData({sub_data:sub_data})
                     },

                     sub_submit(){
                        var edit_data=this.data.sub_data;if(!edit_data){app.err('数据错误');return}
                        fun.get({ac:'phone_sub_submit',data:JSON.stringify(edit_data)}).then(res=>{
                           this.load();
                           this.setData({sub_show:''});
                           app.msg('订阅提交成功');
                        })
                        
                           },
         check_false(e){
            var that=this;
            var list=this.data.arc;
            var data={err:'审核失败'}
            wx.showModal({
              title: '提示',content:'是否审核失败',success(res){
            if(res.confirm){
            fun.get({ac:'adm_arc_false',id:list.id,data:JSON.stringify(data)}).then(res=>{
               //delete(list[index]);
              // that.setData({list:list,f_show:''});
               app.err('审核失败标记成功');
            })
            }
              }
            })
      
      
         },
         copy(e){
var val=e.currentTarget.dataset.val;
wx.setClipboardData({
  data: val,
})

         },
         arc_stop(e){
            var that=this;
            var list=this.data.arc;
            var index=e.currentTarget.dataset.index;
            var data={state:10}
            wx.showModal({
              title: '提示',content:'是否下架该发布，下架后将无法查看到您的发布，但是收藏者仍可以查询到，是否继续？',success(res){
                 if(res.confirm){
                    fun.get({ac:'adm_arc_update',id:list.id,data:JSON.stringify(data)}).then(res=>{
           // delete(list[index]);
            //that.setData({list:list})
            that.load()
                    })
                 }
              }
            })
            },
   onReachBottom() {

   },
   onShareAppMessage: function () {//分享
var set=this.data.set;
      var arc=this.data.arc;//门店
      var img;var title=app.globalData.web+' '+arc.c+'信息';
if(arc.img){
for(var i in arc.img){
   if(!img){img=arc.img[i].img_480}
}

}
if(!img){img=set.emp_bg}
if(!img){img=app.globalData.website+'image/share.png?1';}
 
      var user_id=app.globalData.user_id;if(!user_id){user_id=0;}
      var url='/pages/index/detail?id='+arc.id+'&f='+user_id;
    console.log('分享',img,url)
  this.setData({share_box_show:''});//分享按钮窗口关闭
      return {
        title:title,
        path: url,
        imageUrl: img,
      }
    }, onShareTimeline: function () { 
      var set=this.data.set;
      var arc=this.data.arc;//门店
      var img;var title=app.globalData.web+' '+arc.c+'信息';
if(arc.img){
for(var i in arc.img){
   if(!img){img=arc.img[i].img_480}
}

}
if(!img){img=app.globalData.website+'image/share.png?1';}
  
      var user_id=app.globalData.user_id;if(!user_id){user_id=0;}
      var url='/pages/index/detail?id='+arc.id+'&f='+user_id;
    console.log('分享',img,url)
  this.setData({share_box_show:''});//分享按钮窗口关闭
      return {
        title:title,
        path: url,
        imageUrl: img,
      }
    },go(e){ wx.navigateTo({url: e.currentTarget.dataset.url})},
   back(e){
      var page_num=this.data.page_num;
      console.log(page_num)
      if(page_num<=1 || !page_num){this.home();return;}
      wx.navigateBack({delta:0})},
   home(e){ wx.reLaunch({url: '/pages/index/index'})},
   rgo(e){wx.redirectTo({url: e.currentTarget.dataset.url})},
   login: function (e) {wx.navigateTo({url: '/pages/login/index',})},
   win_open(e){var c=e.currentTarget.dataset.c;this.setData({[c]:'show'})},//打开窗口
   win_close(e){var c=e.currentTarget.dataset.c;this.setData({[c]:''})},//关闭窗口
   hb_close(e){this.setData({hb_show:''})},
   get_hb(e){
var list=this.data.arc;
var that=this;
wx.showLoading({
  title: '正在创建海报，请稍后...',
})

setTimeout(function () {
  wx.hideLoading()
}, 2000);

fun.get({ac:'get_hb',id:list.id}).then(res=>{
wx.hideLoading();
var hb=res.hb;if(!hb){hb=[]}
if(list.img){
for(var i in list.img){
  hb.push({item:list.img[i].img_750,c:'canvas',title:'详情'})
}
console.log(hb)
}
this.setData({hb:hb,hb_show:'show'});
if(list.img){
  setTimeout(function(res){that.draw_hb();},200)
}
})
   },
   hb_change(e){
var val=e.detail.current;
this.setData({hb_index:val})
   },
   hb_save(e){//保存图片
    fun.view_add('保存海报');
    this.setData({is_save_hb:1})
    var index=this.data.hb_index;if(!index){index=0;}
    var arc=this.data.arc;
    var that=this;
var hb=this.data.hb;
var file=hb[index].item;
if(hb[index].c=='img'){
wx.downloadFile({
  url: file,success(res){
   that.setData({is_save_hb:0})
console.log(res)
file=res.tempFilePath
wx.getSetting({success(res){console.log(res)
  //if(res.authSetting['scope.writePhotosAlbum']){
      wx.showLoading({
        title: '海报保存中，请稍后',
      })
   wx.saveImageToPhotosAlbum({filePath:file,success(res){
      wx.hideLoading()
      fun.get({ac:'free_arc',id:arc.id}).then(res=>{

      })

   },complete(){wx.hideLoading()}})
  //}else{app.msg('抱歉，您没有打开保存到本地相册的权限');}
      }})
  }
})
}else{
  wx.getSetting({success(res){console.log(res)
    //if(res.authSetting['scope.writePhotosAlbum']){
        app.msg('图片保存中，请稍后');
     wx.saveImageToPhotosAlbum({filePath:file})
    //}else{app.msg('抱歉，您没有打开保存到本地相册的权限');}
        }})
}
        },
        draw_hb(){//绘制海报
           console.log('开始绘制海报');
        var list=this.data.hb;
        var arc=this.data.arc;
        var that=this;
        fun.get({ac:'get_qr_data',id:arc.id,server:app.globalData.server}).then(res=>{//获取二维码数据
        //获取二维码图片
        this.data.qr=res.qr;
        var canvas=wx.createSelectorQuery().select('#qr').fields({id: true,node: true,size: true}).exec(res=>{
           const canvas = res[0].node;
           var qr_data=canvas.createImage();
           qr_data.src =this.data.qr;
           qr_data.onload = () => {this.data.qr_data=qr_data;//获取二维码数据
              this.setData({hb_show:'show'});
              wx.hideLoading()
              for(var i in list){
if(list[i].c=='canvas'){
                 var query = wx.createSelectorQuery();
                 query.select('#hb_'+i).fields({
                    id: true,
                    node: true,
                    size: true
                  }).exec(this.draw.bind(this));
                }
              }
           }
        
        });
        })
      
        },
        draw(res){var that=this;
           var list=this.data.hb;
           var user=this.data.user;
           var arc=this.data.arc;
           var index=res[0].id.replace('hb_','');
           console.log('海报',res,res[0].id,index)
           const canvas = res[0].node
           const ctx = canvas.getContext('2d')
           const dpr = wx.getSystemInfoSync().pixelRatio;
           var width=750;
           var height=1000;
           if(!this.data.qr_data){//海报数据
           var qr_data=canvas.createImage();
           qr_data.src =this.data.qr;
           qr_data.onload = () => {this.data.qr_data=qr_data;}
        }
        //获取图片信息
        var img = canvas.createImage();
        img.src =list[index].item;
        console.log(img.src)
        img.onload = () => {
        console.log('图片尺寸',img.src,img.width,img.height)
        
        //画板尺寸
        canvas.width = width;
        var img_height=canvas.width*img.height/img.width;//图片的高度
        height=img_height+400;
        canvas.height = height;
        var hb_size=this.data.hb_size;
        if(!hb_size){hb_size={}}
        hb_size[index]={width:Math.ceil(width/1.25),height:Math.ceil(height/1.25)}
        
        this.setData({hb_size:hb_size})
        console.log('高度',img_height,canvas.width,hb_size)
        //背景
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width,  canvas.height);
        ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,img_height);
        
        ctx.moveTo(0,0);
        //标题
        ctx.font = 'normal bold 30px sans-serif';
        ctx.fillStyle = "rgba(0, 0, 0)";
        //文本尺寸
        img_height+=10;
        var line=0;var line_height=50;var metrics=0;
        var lines=[[canvas.width-460,canvas.width-400],[canvas.width-420,canvas.width-370],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50]];
        var title=Array.from(arc.temp)
        //console.log(title)
        var title_data='';
        var text_height=0;
        var text_width=ctx.measureText(arc.temp);
        if(text_width.width<(canvas.width-400)){//直接写入
           console.log('直接写')
           ctx.fillText(arc.temp,30,img_height+line_height);
        }else{
        for(var i in title){
        var line_data=lines[line];
        title_data+=title[i];
        metrics =ctx.measureText(title_data);
        console.log(title_data,line_data,line,metrics)
        if(metrics.width>=line_data[0] && metrics.width<=line_data[1]){//输出
         // console.log('蔬菜')
         text_height=img_height+line_height*(line+1);
         console.log('文本高度',text_height)
           ctx.fillText(title_data,30,text_height);
           title_data='';line++;
           if(line>=5){break;}
        }
        }
        }
        //画圆
        ctx.save();
        ctx.beginPath();
        var x=canvas.width-350;var y=img_height-150;var w=300;var r=150;var h=300;
        ctx.moveTo(x,y);
        ctx.arcTo(x+w,y,x+w,y+h,r);
        ctx.arcTo(x+w,y+h,x,y+h,r);
        ctx.arcTo(x,y+h,x,y,r);
        ctx.arcTo(x,y,x+w,y,r);
        ctx.clip();
        ctx.fillStyle = 'white';
        ctx.fillRect(x, y,w,h);
        ctx.closePath();
        
        //画二维码
        if(this.data.qr_data){
           ctx.drawImage(this.data.qr_data,x+25,y+25,250,250);
        }else{
        var qr_data=canvas.createImage();
        qr_data.src =this.data.qr;
        qr_data.onload = () => {this.data.qr_data=qr_data;
           ctx.drawImage(qr_data,x+25,y+25,250,250);
        }
        }
        
        ctx.restore();
      
        //保存到本地
        setTimeout(function(){
        wx.canvasToTempFilePath({x:0,y:0,canvas:canvas,fileType:'png',success(res){
        that.data['cavans_'+index]=res.tempFilePath;
        console.log('保存本地路径',res,index);
        list[index]['item']=res.tempFilePath;
        that.setData({hb:list})
        }})
      
        },200)
        
        }
        
        
        
        }
        , get_avatar(e){
         var user=this.data.user;if(!user){user={}}
         var user_edit_arr=this.data.user_edit_arr;
         if(!user_edit_arr){user_edit_arr={}}
         var url=e.detail.avatarUrl;
         console.log(e,url)
         fun.file_read(url).then(res=>{
            var data='data:image/jpeg;base64,'+res
            user.logo=data;
            user_edit_arr.logo=res;
            this.data.user_edit_arr=user_edit_arr;
         this.setData({user:user});
         this.submit_user_edit();
         });
      },
      user_nickname_change(e){
         var val=e.detail.value;
         console.log(val);
         var user_edit_arr=this.data.user_edit_arr;
         if(!user_edit_arr){user_edit_arr={}}
         user_edit_arr.nickname=val;
         user_edit_arr.is_change=1;
         this.setData({user_edit_arr:user_edit_arr})
      },submit_user_edit(e){
         var user_edit_arr=this.data.user_edit_arr;if(!user_edit_arr){user_edit_arr={}}
         if(e){
         if(!user_edit_arr['nickname']){app.err('请输入您的昵称');return;}
         }
         fun.get({ac:'user_info_change',data:JSON.stringify(user_edit_arr)}).then(res=>{
this.setData({user_edit_arr:''});
if(e){this.setData({user_change_show:''})}
//
         })
      }

})